package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 162. 寻找峰值
 * @date 2025/9/12 10:31
 */
public class E162 {

    /**
     * 寻找峰值
     *
     * @param nums 数组
     * @return 索引
     */
    public int findPeakElement(int[] nums) {
        if (nums.length == 1) return 0;
        return findPeakElement(nums, 0, nums.length - 1);
    }

    /**
     * 寻找峰值，思路：二分查找
     *
     * @param nums  数组
     * @param begin 开始索引
     * @param end   结束索引
     * @return 索引
     */
    public int findPeakElement(int[] nums, int begin, int end) {
        if (begin > end) return -1;
        int median = (begin + end) >>> 1;
        int left = median - 1 == -1 ? Integer.MIN_VALUE : nums[median - 1];
        int right = median + 1 == nums.length ? Integer.MIN_VALUE : nums[median + 1];
        if (nums[median] > left && nums[median] > right) return median;
        int index = findPeakElement(nums, begin, median - 1);
        if (index == -1) index = findPeakElement(nums, median + 1, end);
        return index;
    }
}
